package com.lq.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lq.entity.Flight;
import com.lq.entity.Order;
import com.lq.mapper.OrderMapper;
import com.lq.mapper.FlightMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author luoqian
 * @date 2022/4/2 16:35
 */
@CrossOrigin
@RestController
@Api(tags = {"订单管理控制层"})
public class OrderController {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private FlightMapper flightMapper;

    @PostMapping("/order/getPage")
    @ApiOperation(value = "分页获取订单信息", notes = "/order/getPage")
    public IPage<Order> getPageStudentInfo(@RequestParam @ApiParam(name = "pageNum", value = "pageNum", required = true) int pageNum, @RequestParam @ApiParam(name = "pageSize", value = "pageSzie", required = true) int pageSize, @RequestBody @ApiParam(name = "order", value = "order", required = true) Order order) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        if(!("").equals(order.getFlightNo())){
            queryWrapper.like("flight_no",order.getFlightNo());
        }
        if(!("").equals(order.getUsername())){
            queryWrapper.eq("username",order.getUsername());
        }
        Page<Order> orderPage = new Page<>(pageNum, pageSize);
        return orderMapper.selectPage(orderPage, queryWrapper);
    }

    @PostMapping("/order/insert")
    @ApiOperation(value = "购票", notes = "/order/insert")
    public int orderInsert(@RequestBody @ApiParam(name = "order对象", value = "order", required = true) Order order) {
        QueryWrapper<Flight> query = new QueryWrapper<>();
        query.eq("flight_no", order.getFlightNo());
        Flight flights = flightMapper.selectOne(query);
        Integer ticket = flights.getTicket();
        flights.setTicket(ticket - 1);
        flightMapper.updateById(flights);
        return orderMapper.insert(order);
    }

    @PostMapping("/order/refundTicket")
    public int refundTicket(@RequestBody @ApiParam(name = "order对象", value = "order", required = true) Order order) {
        order.setStatus("已退票");
        QueryWrapper<Flight> queryWrapper = new QueryWrapper();
        queryWrapper.eq("flight_no",order.getFlightNo());
        Flight flight = flightMapper.selectOne(queryWrapper);
        Integer ticket = flight.getTicket();
        flight.setTicket(ticket + 1);
        flightMapper.updateById(flight);
        return orderMapper.updateById(order);
    }
}
